package com.nanfeng.screenshot.service.impl;

import com.nanfeng.screenshot.enums.ChengduHousingEnum;
import com.nanfeng.screenshot.service.ScreenshotService;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.openqa.selenium.WebDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.UUID;

/**
 * @ClassName：ScreenshotServiceImpl
 * @Author: LiuYunZhao
 * @Date: 2025/7/11 9:01
 * @Description: 截图工具服务层
 */
@Service
public class ScreenshotServiceImpl implements ScreenshotService {

    private static final Logger logger = LoggerFactory.getLogger(ScreenshotServiceImpl.class);

    @Resource
    private  WebDriver webDriver;

    /**
     * 保存截图并加压
     * @param list
     * @return
     * @throws IOException
     */
    @Override
    public String saveScreenshotAndZip(List<ChengduHousingEnum> list) throws IOException {
        /**
         * 1.创建临时目录存放截图
         */
        String tempDir = createTempDirectory();
        logger.info("创建临时目录: {}", tempDir);


        /**
         * 2.对每个URL进行截图
         */
        for (ChengduHousingEnum chengduHousingEnum : list) {
            captureScreenshot(chengduHousingEnum, tempDir);
        }

        /**
         * 3.关闭浏览器
         */
        webDriver.quit();

        /**
         * 4.创建ZIP文件
         */
        String zipFilePath = createZipFile(tempDir);
        logger.info("ZIP文件已创建: {}", zipFilePath);

        /**
         * 清理临时目录
         */
        deleteDirectory(new File(tempDir));
        logger.info("临时目录已删除");

        return zipFilePath;
    }


    /**
     * 创建临时目录存放截图
     * @return
     */
    @Override
    public String createTempDirectory() {
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        String tempDir = "D:/screenshot_temp_" + timestamp;
        new File(tempDir).mkdirs();
        return tempDir;
    }

    /**
     * 对每个URL进行截图
     * @param chengduHousing
     * @param outputDir
     */
    @Override
    public void captureScreenshot(ChengduHousingEnum chengduHousing, String outputDir) {
        try {
            /**
             * 1.访问URL
             */
            webDriver.get(chengduHousing.getUrl());
            // 等待页面加载
            Thread.sleep(3000);

            /**
             * 2.获取屏幕尺寸并截图
             */
            Robot robot = new Robot();
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            Rectangle screenRect = new Rectangle(screenSize);
            BufferedImage image = robot.createScreenCapture(screenRect);

            /**
             * 3.生成文件名（包含URL的部分信息）
             */
            String fileName = chengduHousing.getFileName();
            String filePath = outputDir + File.separator + fileName;

            /**
             * 保存截图
             */
            File outputFile = new File(filePath);
            ImageIO.write(image, "PNG", outputFile);
            logger.info("截图已保存: {}", filePath);

        } catch (Exception e) {
            logger.error("截图失败: {}", chengduHousing.getUrl(), e);
        }
    }


    /**
     * 加压文件
     * @param sourceDir
     * @return
     * @throws IOException
     */
    @Override
    public String createZipFile(String sourceDir) throws IOException {
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        String zipFilePath = "D:/screenshots_" + timestamp + ".zip";

        try (ZipArchiveOutputStream zaos = new ZipArchiveOutputStream(new FileOutputStream(zipFilePath))) {
            Path sourcePath = Paths.get(sourceDir);

            Files.walk(sourcePath)
                    .filter(path -> !Files.isDirectory(path))
                    .forEach(path -> {
                        try {
                            String entryName = sourcePath.relativize(path).toString();
                            ZipArchiveEntry entry = new ZipArchiveEntry(entryName);
                            zaos.putArchiveEntry(entry);

                            byte[] buffer = new byte[4096];
                            try (InputStream is = Files.newInputStream(path)) {
                                int bytesRead;
                                while ((bytesRead = is.read(buffer)) != -1) {
                                    zaos.write(buffer, 0, bytesRead);
                                }
                            }
                            zaos.closeArchiveEntry();
                        } catch (IOException e) {
                            logger.error("添加文件到ZIP失败: {}", path, e);
                        }
                    });
        }

        return zipFilePath;
    }

    /**
     * 删除文件
     * @param directory
     */
    @Override
    public void deleteDirectory(File directory) {
        File[] contents = directory.listFiles();
        if (contents != null) {
            for (File file : contents) {
                if (!Files.isSymbolicLink(file.toPath())) {
                    deleteDirectory(file);
                }
            }
        }
        directory.delete();
    }
}    